package user

import (
	"context"
	"strings"

	"mall/common/errorx"
	"mall/common/jwtx"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateUserLogic) CreateUser(req *types.CreateUserRequest) (resp *types.CreateUserResponse, err error) {
	if len(strings.TrimSpace(req.Username)) == 0 {
		return nil, errorx.Error(errorx.ERROR_USERNAME_REQUIRED, "")
	}

	adminId, _ := jwtx.GetUserId(l.ctx)

	res, err := l.svcCtx.BackendRpc.BackendCreateUser(l.ctx, &backendclient.CreateUserRequest{
		Username:  req.Username,
		Nickname:  req.Nickname,
		Name:      req.Name,
		Email:     req.Email,
		Mobile:    req.Mobile,
		Status:    req.Status,
		DeptId:    req.DeptId,
		RoleId:    req.RoleId,
		CreatedBy: adminId,
	})
	if err != nil {
		return nil, err
	}

	return &types.CreateUserResponse{
		Status:   "ok",
		Message:  "添加用户成功，初始密码为："+res.Password,
		Password: res.Password,
	}, nil
}
